$(function() {
    $('#calendar').fullCalendar({
        header: {
            left: 'agendaDay,agendaWeek',
            center: 'prev title next',
            right: 'today'
        },
        views: {
            agendaDay: {
                groupByResource: true
            }
        },
        resources: [],
        droppable: true,
        defaultView: 'agendaWeek',
        allDaySlot: false,
        navLinks: true,
        selectable: true,
        selectHelper: true,
        editable: true,
        eventLimit: true,
        defaultDate: $('#timeValue').val(),
        lazyFetching: true,
        handleWindowResize: true,
        nowIndicator: true,
        titleFormat: 'YYYY-MM-DD',
        minTime: "07:00:00",
        maxTime: "20:00:00",
        height: window.innerHeight - 35,
        slotDuration: "00:15:00",
        slotLabelFormat: 'HH',
        slotLabelInterval: "00:60:00",
        slotLabelFormats: 'mm',
        slotLabelIntervals: "00:15:00",
        selectMinDistance: 30,
        timeFormat: 'H:mm',
        slotEventOverlap: false,
        schedulerLicenseKey: 'CC-Attribution-NonCommercial-NoDerivatives',
        dragRevertDuration: 200,
        unselectAuto: false,
        groupByResource: false,
        groupByDateAndResource: false,
        windowResize: function(view) {
            $('#calendar').fullCalendar('option', 'height', window.innerHeight - 52)
        },
        select: function(startDate, endDate, jsEvent, view, resource) {
            var start = startDate.format('YYYY-MM-DD HH:mm');
            var end = endDate.format('YYYY-MM-DD HH:mm');
            var start1 = new Date(start);
            var end1 = new Date(end);
            var continued = parseInt(end1 - start1) / 1000 / 60;
            var docName;
            if (view.type == 'agendaDay') {
                docName = resource.title
            } else {
                docName = ''
            } if (docName != '') {
                var eventData = start + "," + end + "," + docName + "," + continued;
                var index = layer.open({
                    type: 2,
                    title: '添加预约客户',
                    area: ['60%', '90%'],
                    fix: true,
                    maxmin: true,
                    content: Feng.ctxPath + '/reservationTcView/doctor_addTaskTcMarket/' + eventData
                });
                this.layerIndex = index
            }
            $('#calendar').fullCalendar('unselect')
        },
        events: function(start, end, timezone, callback) {
            var startTime = start.format('YYYY-MM-DD HH:mm:ss');
            var ends = new Date(end.format('YYYY-MM-DD HH:mm:ss'));
            var YY = ends.getFullYear();
            var MM = ends.getMonth() + 1;
            var DD = ends.getDate() - 1;
            if (MM < 10) {
                MM = "0" + MM
            };
            if (DD < 10) {
                DD = "0" + DD
            };
            var endTime = YY + "-" + MM + "-" + DD + " 23:59:59";
            var tcId = $("#tcId").val();
            var tcName = $("#tcName").val();
            var timeSlot = startTime + "," + endTime + "," + tcId;
            $.ajax({
                url: Feng.ctxPath + '/reservationTcView/getDataTc/' + timeSlot,
                dataType: 'json',
                type: 'POST',
                success: function(data) {
                    var events = [];
                    $.each(data, function(key, value) {
                        var obj = {
                            id: value.customerId,
                            title: value.appointmentPayService,
                            start: new Date(Date.parse(value.startTime)),
                            end: new Date(Date.parse(value.endTime)),
                            customerName: value.customerName,
                            resourceId: value.id,
                            medicalRecordNumber: value.medicalRecordNumber,
                            customerPhone: value.customerPhone,
                            customerAge: value.customerAge,
                            doctor: value.doctor,
                            arrivalStore: value.arrivalStore,
                            fieldTc: value.fieldTc,
                            remarksReservation: value.remarksReservation,
                            firstVisitDate: value.firstVisitDate,
                            filingTime: value.filingTime,
                            archiving: value.archiving,
                            birthday: value.birthday,
                            createAppointmentTime: value.createAppointmentTime,
                            arrivalStatus: value.arrivalStatus,
                            customerStatus: value.customerStatus,
                            reservationsId: value.reservationsId,
                            accountarrears: value.accountarrears,
                            todaySum: value.todaySum,
                            aftersSum: value.aftersSum,
                            beforeSum: value.beforeSum,
                            yellowNumber: value.yellowNumber,
                            sex: value.sex,
                            remarks: value.remarks
                        };
                        if (value.arrivalStatus == '1') {
                            obj.backgroundColor = "#4bbcff";
                            obj.borderColor = "white"
                        } else if (value.arrivalStatus == '2') {
                            obj.backgroundColor = "#10428b";
                            obj.borderColor = "white"
                        } else if (value.arrivalStatus == '3') {
                            obj.backgroundColor = "#ffba40";
                            obj.borderColor = "white"
                        } else if (value.arrivalStatus == '4') {
                            obj.backgroundColor = "#2dc87e";
                            obj.borderColor = "white"
                        } else if (value.arrivalStatus == '5') {
                            obj.backgroundColor = "#61b740";
                            obj.borderColor = "white"
                        } else if (value.arrivalStatus == '6') {
                            obj.backgroundColor = "#017cdc";
                            obj.borderColor = "white"
                        } else if (value.arrivalStatus == '7') {
                            obj.backgroundColor = "gray";
                            obj.borderColor = "white"
                        } else if (value.arrivalStatus == '9') {
                            obj.backgroundColor = "#4bbcff";
                            obj.borderColor = "white"
                        } else if (value.arrivalStatus == '10') {
                            obj.backgroundColor = "#017cdc";
                            obj.borderColor = "white"
                        } else if (value.arrivalStatus == '13') {
                            obj.backgroundColor = "#FDAEBE";
                            obj.borderColor = "white"
                        } else if (value.arrivalStatus == '14') {
                            obj.backgroundColor = "#FDAEBE";
                            obj.borderColor = "white"
                        }
                        events.push(obj)
                    });
                    callback(events)
                }
            });
            $.ajax({
                url: Feng.ctxPath + '/reservationTcView/getTcWeekSchedul/' + timeSlot,
                dataType: 'json',
                type: 'POST',
                success: function(data) {
                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            if (new Date(data[i].theDate).getDay() == 0) {
                                $('#calendar .fc-time-grid td.fc-day').eq(6).css("background", "#eeeeee")
                            } else if (new Date(data[i].theDate).getDay() == 1) {
                                $('#calendar .fc-time-grid td.fc-day').eq(0).css("background", "#eeeeee")
                            } else if (new Date(data[i].theDate).getDay() == 2) {
                                $('#calendar .fc-time-grid td.fc-day').eq(1).css("background", "#eeeeee")
                            } else if (new Date(data[i].theDate).getDay() == 3) {
                                $('#calendar .fc-time-grid td.fc-day').eq(2).css("background", "#eeeeee")
                            } else if (new Date(data[i].theDate).getDay() == 4) {
                                $('#calendar .fc-time-grid td.fc-day').eq(3).css("background", "#eeeeee")
                            } else if (new Date(data[i].theDate).getDay() == 5) {
                                $('#calendar .fc-time-grid td.fc-day').eq(4).css("background", "#eeeeee")
                            } else if (new Date(data[i].theDate).getDay() == 6) {
                                $('#calendar .fc-time-grid td.fc-day').eq(5).css("background", "#eeeeee")
                            }
                        }
                    }
                }
            });
            $('#calendar').fullCalendar('addResource', {
                id: tcId,
                title: tcName
            })
        },
        eventClick: function(calEvent, jsEvent, view) {
            arr = calEvent;
            $('a').removeClass('shadow');
            $(this).css("border-color", "white ");
            $(this).addClass('shadow');
            var start = calEvent.start.format('YYYY-MM-DD');
            var starts = calEvent.start.format('HH:mm');
            var end = calEvent.end.format('HH:mm');
            var date = new Date();
            var time = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
            var startTime = new Date(start.replace("-", "/").replace("-", "/"));
            var endtime = new Date(time.replace("-", "/").replace("-", "/"));
            jsEvent.stopPropagation();
            $(this).attr('id', calEvent.id);
            var eds = "";
            eds += '<div style="color: #555555;padding-top: 3px;"><div style="display: flex">';
            if (calEvent.customerAge == "" || calEvent.customerAge == null || calEvent.customerAge == "null") {
                eds += '<div><img src="${ctxPath}/static/img/unkown-sex.png" alt="" width="50px;"></div>'
            } else if (calEvent.customerAge >= 0 && calEvent.customerAge < 18) {
                if (calEvent.sex == "男") {
                    eds += '<div><img src="' + Feng.ctxPath + '/static/img/nan-child.png" alt="" width="50px;"></div>'
                } else if (calEvent.sex == "女") {
                    eds += '<div><img src="' + Feng.ctxPath + '/static/img/nv-child.png" alt="" width="50px;"></div>'
                } else {
                    eds += '<div><img src="' + Feng.ctxPath + '/static/img/unkown-sex.png" alt="" width="50px;"></div>'
                }
            } else if (calEvent.customerAge >= 18 && calEvent.customerAge <= 50) {
                if (calEvent.sex == "男") {
                    eds += '<div><img src="' + Feng.ctxPath + '/static/img/male-adult.png" alt="" width="50px;"></div>'
                } else if (calEvent.sex == "女") {
                    eds += '<div><img src="' + Feng.ctxPath + '/static/img/lfemale-child.png" alt="" width="50px;"></div>'
                } else {
                    eds += '<div><img src="' + Feng.ctxPath + '/static/img/unkown-sex.png" alt="" width="50px;"></div>'
                }
            } else if (calEvent.customerAge > 50) {
                if (calEvent.sex == "男") {
                    eds += '<div><img src="' + Feng.ctxPath + '/static/img/male-old.png" alt="" width="50px;"></div>'
                } else if (calEvent.sex == "女") {
                    eds += '<div><img src="' + Feng.ctxPath + '/static/img/female-old.png" alt="" width="50px;"></div>'
                } else {
                    eds += '<div><img src="' + Feng.ctxPath + '/static/img/unkown-sex.png" alt="" width="50px;"></div>'
                }
            };
            eds += '<div style="flex: 1;margin-left: 10px;"><div><span style="color: #319dbc;font-size: 16px;font-weight: bold;padding-left: 2px;cursor:pointer;" onclick="openBilee(' + "'" + calEvent.id + "'" + ')">' + calEvent.customerName + '</span><span style="font-size: 14px;margin: 0 11px;">' + calEvent.arrivalStore + '</span><span style="font-size: 14px;">' + calEvent.customerStatus + '</span></div><div><span>' + calEvent.medicalRecordNumber + '</span></div><div><span>' + start + '(' + calEvent.doctor + ')</span></div><div style="font-size: 14px;font-weight: bolder"><span>' + calEvent.customerPhone + '</span><span>/' + calEvent.sex + '</span><span>/' + calEvent.customerAge + '</span></div></div></div>';
            if (calEvent.remarks != "") {
                eds += '<div>备注：<span>' + calEvent.remarks + '</span></div>'
            };
            eds += '<div style="color: #319DB5;position: relative;cursor: pointer"><span onclick="getMakeNumer(' + "'" + calEvent.reservationsId + "'" + ')">今日预约【<span>' + calEvent.todaySum + '</span>】</span><span onclick="getMakeNumer(' + "'" + calEvent.reservationsId + "'" + ')">之后预约【<span>' + calEvent.aftersSum + '</span>】</span><span onclick="getMakeNumer(' + "'" + calEvent.reservationsId + "'" + ')">之前预约【<span>' + calEvent.beforeSum + '</span>】</span><a href="javascript:;" id="takeOne" onclick="takeOne()" style="color: #319DB5;position: absolute;right: 0;top: 0;display: none">返回<span class="glyphicon glyphicon-share-alt"></span></a></div><div style="border-top: 1px solid #cccccc"><ul class="ulBox">' +
                '<li><span>预约时间</span><span style="color: black;font-weight: bold;font-size: 18px;">' + starts + '-' + end + '</span></li>' +
                '<li><span>预约医生</span><span>' + calEvent.doctor + '</span></li>' +
                '<li><span>看诊项目</span><span style="display: inline-block;width: 140px;">' + calEvent.title + '</span><a style="color: brown" href="javascript:;" onclick="updAppointmentPayService(' + "'" + calEvent.id + "'" + ')">修改</a></li>' +
                '<li style="vertical-align:middle;"><span style="vertical-align: text-bottom;">预约备注</span><span title="' + calEvent.remarksReservation + '" style="display: inline-block;width: 140px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">' + calEvent.remarksReservation + '</span><a style="color: brown" href="javascript:;" onclick="updRemarksReservation(' + "'" + calEvent.id + "'" + ')">修改</a></li>' +
                '<li><span>初诊日期</span><span>' + calEvent.firstVisitDate + '</span></li>' +
                '<li><span>创建时间</span><span>' + calEvent.createAppointmentTime + '</span></li>' +
                '<li><span>创建人</span><span style="display: inline-block;width: 90px;">' + calEvent.archiving + '</span><a style="color: brown" href="javascript:;" onclick="getUpdateLog(' + "'" + calEvent.id + "'" + ')">改动日志</a></li>' +
                '<li><span>黄页编号</span><span style="display: inline-block;width: 90px;">' + calEvent.yellowNumber + '</span></li>' +
                '</ul><div style="display: none" id="bookingBox"></div></div></div>';

            if(calEvent.arrivalStatus === '1' || calEvent.arrivalStatus === '9' ){
                var ads = '<div class="btnBox">' +
                    '<button type="button" class="btn" onclick="sureAppointment(' + "'" + calEvent.id + "','" + calEvent.customerName + "'" + ',arr)">确定</button> ' +
                    // '<button type="button" class="btn" onclick="cancelAppointment(' + "'" + calEvent.id + "','" + calEvent.customerName + "'" + ',arr)">取消</button> ' +
                    '<button type="button" class="btn" onclick="shortMessage(' + "'" + calEvent.id + "'" + ')" style="margin-top: 5px;">短信</button> </div>';
            }
            test = layer.open({
                type: 4,
                tips: [2, '#ffffff'],
                closeBtn: 0,
                area: ['305px', 'auto'],
                content: ['<div>' + eds + '' + ads + '</div>', '#' + calEvent.id + ''],
                success: function (layero, index) {
                    if (($(layero).offset().top + $(layero).height()) > $(window).height()) {
                        $(layero).css("top", ($(window).height() - ($(layero).height() + 10)))
                    }
                }
            })
        },
        eventRender: function(calEvent, element, view) {
            if (calEvent.customerName == "" || calEvent.customerName == null) {
                element.prepend("<div class='myfc-title'><span>新建预约</span></div>")
            }
        },
        eventAfterRender: function(calEvent, element, view) {
            if (element[0].clientWidth < 24) {
                element[0].innerHTML = ""
            } else if (element[0].clientWidth >= 24 && element[0].clientWidth < 45) {
                element[0].innerHTML = "";
                element.prepend("<div class='myfc-title'><span style='font-size: 15px;font-weight: bold;letter-spacing: 2px;'>" + calEvent.customerName + "</span></div>")
            } else {
                if (calEvent.accountarrears != 0) {
                    element.prepend("<div class='myfc-title'><span style='font-size: 15px;font-weight: bold;letter-spacing: 2px;'>" + calEvent.customerName + "</span></div><div style='position: absolute;bottom: 5px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;'>" + calEvent.remarksReservation + "</div><div style='position: absolute;right: 2px;top: 1px;color: white;background: red;padding: 0 2px;border: 1px solid white;border-radius: 50%;font-size: 0.5em'>欠</div>")
                } else {
                    element.prepend("<div class='myfc-title'><span style='font-size: 15px;font-weight: bold;letter-spacing: 2px;'>" + calEvent.customerName + "</span></div><div style='position: absolute;bottom: 5px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;'>" + calEvent.remarksReservation + "</div>")
                }
            }
        },
        eventDrop: function(event, delta, revertFunc, jsEvent, ui, view) {
            if (event.arrivalStatus == '5' || event.arrivalStatus == '7') {
                alert("此状态不能修改！");
                revertFunc()
            } else {
                if (confirm("您确定要修改预约么？")) {
                    var startTime = event.start.format('YYYY-MM-DD HH:mm:ss');
                    var endTime = event.end.format('YYYY-MM-DD HH:mm:ss');
                    var tcId = event.resourceId;
                    var id = event.id;
                    var sed = startTime + "," + endTime + "," + tcId + "," + id;
                    $.ajax({
                        url: Feng.ctxPath + '/reservationTcView/updateViewsTc/' + sed,
                        dataType: 'json',
                        type: 'POST',
                        success: function(data) {
                            Feng.success('修改成功!')
                        },
                        error: function(data) {
                            revertFunc()
                        }
                    })
                } else {
                    revertFunc()
                }
            }
        },
        eventResize: function(event, delta, revertFunc, jsEvent, ui, view) {
            if (event.arrivalStatus == '5' || event.arrivalStatus == '7') {
                alert("此状态不能修改！");
                revertFunc()
            } else {
                if (confirm("您确定要修改预约么？")) {
                    var startTime = event.start.format('YYYY-MM-DD HH:mm:ss');
                    var endTime = event.end.format('YYYY-MM-DD HH:mm:ss');
                    var tcId = event.resourceId;
                    var id = event.id;
                    var sed = startTime + "," + endTime + "," + tcId + "," + id;
                    $.ajax({
                        url: Feng.ctxPath + '/reservationTcView/updateViewsTc/' + sed,
                        dataType: 'json',
                        type: 'POST',
                        success: function(data) {
                            Feng.success('修改成功!')
                        },
                        error: function(data) {
                            revertFunc()
                        }
                    })
                } else {
                    revertFunc()
                }
            }
        },
        loading: function(isLoading, view) {
            if (isLoading == true) {
                $(".fc-prev-button,.fc-next-button").css("pointer-events", "none")
            } else if (isLoading == false) {
                $(".fc-prev-button,.fc-next-button").css("pointer-events", "auto")
            }
        }
    });
    $("#calendar").on('click', 'h2', function() {
        laydate({
            istime: true,
            format: 'YYYY-MM-DD',
            choose: function(value) {
                $('#calendar').fullCalendar('gotoDate', value)
            }
        })
    })
});
returnView = function() {
    window.location = Feng.ctxPath + "/customer/customer_reservationRMTcViews"
};